package cc.yuxiang.spider.fanhao;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.text.StrFormatter;
import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.io.FileUtil;
import jodd.io.findfile.FindFile;
import jodd.io.findfile.WildcardFindFile;
import jodd.jerry.Jerry;
import jodd.util.Wildcard;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@RequiredArgsConstructor
public class Fanhao {
	private @NonNull String dirVideo;
	private static final String urlBase = "https://www.javbus.icu";
	
	public void move(List<File> videos,File targetDir) throws IOException {
		mkdir(targetDir);
		videos.forEach(v -> {
			String fileName = cn.hutool.core.io.FileUtil.mainName(v);
			String starName = this.findStarName(fileName);
			try {
				if(starName == null) {
					log.info("没有找到明星:{}",fileName);
					return;
				}
				File dirStartName = new File(targetDir.getAbsoluteFile()+"/" + starName);// 明星的文件夹
				mkdir(dirStartName);
				log.info("----移动文件中....");
				TimeInterval timer = DateUtil.timer();
				FileUtil.move(v, dirStartName);
//				cn.hutool.core.io.FileUtil.move(v, dirStartName, false);
				log.info("移动{} -> {},完成:{}秒",starName,dirStartName,timer.intervalSecond());
			} catch (IOException e) {
				log.error("io异常", e);
			}
		});
		log.info("执行完成!!");
	}

	public List<File> findVideos() {
		FindFile ff = new WildcardFindFile();
		ff.matchType(WildcardFindFile.Match.NAME);
//		ff.exclude("._*");
		ff.include("*.mp4","*.avi","*.mkv");
		ff.recursive(false);// 递归
		ff.includeDirs(false);
		ff.searchPath(dirVideo);
		return ff.findAll().stream().filter(f->!Wildcard.matchPath(f.getName(), "._*")).collect(Collectors.toList());
	}

	public String findStarName(String fh) {
		TimeInterval timer = DateUtil.timer();
		HttpBrowser browser = new HttpBrowser();
		String url = StrFormatter.format("{}/{}", urlBase, fh);
		HttpResponse sendRequest = browser.sendRequest(HttpRequest.get(url));
		String bodyText = sendRequest.bodyText();
		Jerry $doc = Jerry.jerry(bodyText);
		String starName = $doc.$("div.star-name").$("a").text();
		if ("".equals(starName)) {
			starName = null;
		}
		log.info("查找=耗时:{}毫秒,番号:{}查询到明星:{}", timer.interval(), fh, starName);
		return starName;
	}
	
	
	private void mkdir(File dirStartName) throws IOException {
		if (!FileUtil.isExistingFolder(dirStartName)) {
			log.info("创建文件夹:"+dirStartName);
			FileUtil.mkdir(dirStartName);	
		}
	}
}
